package cn.jas.common.jascommon.util;
import org.apache.tomcat.util.codec.binary.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;

/**
 * @description: aes加密
 * @author: chen_mx
 **/
public class EncryptUtil {

    private static final String CipherMode="AES/CBC/PKCS5Padding";

    private static final String SecretKey="debug";

    private static final Integer IVSize=16;

    private static final String EncryptAlg ="AES";

    private static final String Encode="UTF-8";

    private static final int SecretKeySize=16;

    private static final String Key_Encode="UTF-8";

    /**
     * 创建密钥
     * @return
     */
    private static SecretKeySpec createKey(){
        StringBuilder sb=new StringBuilder(SecretKeySize);
        sb.append(SecretKey);
        if (sb.length()>SecretKeySize){
            sb.setLength(SecretKeySize);
        }
        if (sb.length()<SecretKeySize){
            while (sb.length()<SecretKeySize){
                sb.append(" ");
            }
        }
        try {
            byte[] data=sb.toString().getBytes(Encode);
            return new SecretKeySpec(data, EncryptAlg);
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 创建16位向量: 不够则用0填充
     * @return
     */
    private static IvParameterSpec createIV() {
        StringBuffer sb = new StringBuffer(IVSize);
        sb.append(SecretKey);
        if (sb.length()>IVSize){
            sb.setLength(IVSize);
        }
        if (sb.length()<IVSize){
            while (sb.length()<IVSize){
                sb.append("0");
            }
        }
        byte[] data=null;
        try {
            data=sb.toString().getBytes(Encode);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return new IvParameterSpec(data);
    }

    /**
     * 加密：有向量16位，结果转base64
     * @param context
     * @return
     */
    public static String encrypt(String context) {
        try {
            byte[] content=context.getBytes(Encode);
            SecretKeySpec key = createKey();
            Cipher cipher = Cipher.getInstance(CipherMode);
            cipher.init(Cipher.ENCRYPT_MODE, key, createIV());
            byte[] data = cipher.doFinal(content);
            String result= Base64.encodeBase64String(data);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /*** 有向量的方式**/
    public static String encrypt(String context,String key1,String  iv) {
        try {
            byte[] content=context.getBytes(Encode);
            SecretKeySpec key = new SecretKeySpec(key1.getBytes(Encode), EncryptAlg);
            Cipher cipher = Cipher.getInstance(CipherMode);
            cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv.getBytes(Encode)));
            byte[] data = cipher.doFinal(content);
            String result= Base64.encodeBase64String(data);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解密
     * @param context
     * @return
     */
    public static String decrypt(String context) {
        try {
            byte[] data= Base64.decodeBase64(context);
            SecretKeySpec key = createKey();
            Cipher cipher = Cipher.getInstance(CipherMode);
            cipher.init(Cipher.DECRYPT_MODE, key, createIV());
            byte[] content = cipher.doFinal(data);
            String result=new String(content,Encode);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /** 解密 iv**/
    public static String decrypt(String context,String  key1,String iv) {
        try {
            byte[] data= Base64.decodeBase64(context);
            SecretKeySpec key = new SecretKeySpec(key1.getBytes(Encode), EncryptAlg);
            Cipher cipher = Cipher.getInstance(CipherMode);
            cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv.getBytes(Encode)));
            byte[] content = cipher.doFinal(data);
            String result=new String(content,Encode);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /** Base64 加密**/
    public  static String   BaseEncode(String  resource){
        byte[] res= java.util.Base64.getEncoder().encode(resource.getBytes());
        return  new String(res);
    }

    public  static  String  BaseDecode(String  resource) {
        byte[]  res=java.util.Base64.getDecoder().decode(resource);
        return  new  String(res);
    }


    public static void main(String[] args) throws Exception{
        //密钥 加密内容(对象序列化后的内容-json格式字符串)
        //String content="{\"domain\":{\"method\":\"getDetails\",\"url\":\"http://www.baidu.com\"},\"name\":\"steadyjack_age\",\"age\":\"23\",\"address\":\"Canada\",\"id\":\"12\",\"phone\":\"15627284601\"}";

        //System.out.println(BaseDecode( "lTrrOdC+WJJpM2PibtVhu/7eWXl7AL/HWMaxqnY859K56QdLCjlkUcyYDR4BqgdrLGAJrPTHYyLbimjv30ngGp3thoofTD4V3u2/pg9zh/s+9CP4HsYD9L0HdG3ym9AcD9p3jfLz6qhWDMoRZRhGtbdT6NDgiotATGQ4qSN/HcNfMeSVofWHQ2nCECVMXBuLbJukLc3RGWws7L5A81kEh3J4AzAMHu4hJf/GqP+3iWNKIXr4k0SdT2hP2KuqCavS6J0qyplWYbl7zRzcwCiTHlyt/Ufc/I13pPeyb5UGG/AOvc1kT42pi19Uu2FUGDwA+PXun8pLiQs/qwl9mbaBK4c8vDdvF6tnglQHx0bb1+aaD246BNbLM1YZiPpS5VluBqqR9qYlO+hKhOafpmgXXA=="));
        System.out.println(decrypt("NTc1MDA2LTMzODEtMC17Im9yZGVySWQiOiIyMDE5MTAxODE5Mzc1MjFmMzNjNWM1YjBmMDQ0YTVhnNzc2ZWMxMzZmYWY5YmE2IiwiY3JlYXRlVGltZSI6IjIwMTkxMDE4MTkzNzUyIiwiaWNvblVSTCI6nIiIsInVzZXJOYW1lIjoi5rWL6K+VMiIsInVzZXJJZCI6ImNlc2hpMiIsIm9yZGVyTmFtZSI6IuOAnkOmjjumZqeagh+WHhuW6k+OAkTIwMTkxMDE4MTkzNyJ9"));


        String  content="565006-3377-0-{\"orderId\":\"20191018185604daaefda9a7d04514939d8e0e6ed940e3\",\"createTime\":\"20191018185604\",\"iconURL\":\"\",\"userName\":\"测试2\",\"userId\":\"ceshi2\",\"orderName\":\"【风险标准库】测试2019181852001\"}";
        String  bastEncode=BaseEncode(content);
        System.out.println(bastEncode);
        System.out.println(BaseDecode(bastEncode));

        String encryptText=encrypt(content);
//        String decryptText=decrypt(encryptText);
//        System.out.println(String.format("明文：%s \n加密结果：%s \n解密结果：%s ",content,encryptText,decryptText));
//
//        String  test=BaseEncode(content);
//        System.out.println("tes@"+test);
//        String  res=BaseDecode(test);
//        System.out.println(res);
//        String testt=decrypt(encryptText);
//        System.out.println(testt);
       /* String  result="uzMo/URBG28ygAufPsO3Lw==";
        String  key="AA62EFAZCeR87QdG";
        String  iv="y2PCJjYE74GQFPyN";
        String decryptText1  =decrypt(result,key,iv);
        System.out.println("解密结果:"+decryptText1);*/


    }

}
